package com.ly.cyclictest.test01;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;

public class Soldier implements Runnable {

    private String soldier;

    private final CyclicBarrier cyclicBarrier;

    public Soldier(String soldier,CyclicBarrier cyclicBarrier) {
        this.soldier = soldier;
        this.cyclicBarrier=cyclicBarrier;
    }

    @Override
    public void run() {
        try {

            //士兵集合--等待全部士兵集合完毕
            cyclicBarrier.await();
            //集合完毕执行任务
            doWork();
            //任务执行完成,等待其他士兵
            cyclicBarrier.await();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    void doWork(){
        try {
            Thread.sleep(Math.abs(new Random().nextInt(10000)));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(soldier+"士兵执行任务完成");
    }
}
